var express = require('express')
var app = express()
var fs = require('fs')
var mysql = require('mysql')
var cors = require('cors')

// 设置跨域访问
app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    res.header('Content-Type', 'application/json;charset=utf-8')
    next()
})

app.use(
    cors({
        origin: ['http://localhost:3000'],
        methods: ['get', 'post'],
        allowedHeaders: ['Content-Type', 'Authorization']
    })
)

//设置数据库连接属性
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'ca1le1',
    port: '3306',
    database: 'train1'
})

db.connect(err => {
    if (err) throw err
    console.log('连接成功')
})

//前端访问路由
//localhost:3000/schoolpm
app.get('/schoolpm', (req, res) => {
        //数据库查询
        let sql = 'SELECT school_name,qk_count FROM school_all ORDER BY qk_count desc LIMIT 5'
        db.query(sql, (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.json(result)
            }
        })
    })

app.get('/test', (req, res) => {
        //数据库查询
        res.json({msg: 'I\'m from express...'});
    })
	
    //服务端监听地址
var server = app.listen(3000, function() {
    var host = server.address().address
    var port = server.address().port
    console.log(host, port)
})